package com.lisp.dl.main;

import java.io.File;

import org.apache.commons.io.FileUtils;

import com.lisp.dl.ModuleManager;

public class Main {
	
	public static void main(String args[]) throws Exception {
		// 启动监控线程
		new Thread(new DynamicLoader()).start();
		
		// 循环打印
		while(true) {
			ModuleManager.get("PrintModule").process();
			Thread.sleep(3000);
		}
	}
	
	static class DynamicLoader implements Runnable {

		private final String REPOSITORY = "target/classes";
		
		private long oldLastModified = -1;
		
		@Override
		public void run() {
			while(true) {
				try {
					reloadIfModified();
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		private void reloadIfModified() throws Exception {
			String implClassFileName = "com.lisp.dl.module.impl.PrintModuleVersion"
					.replace('.', File.separatorChar) + ".class";
			File file = FileUtils.getFile(new File(REPOSITORY), implClassFileName);
			long newLastModified = file.lastModified();
			if(newLastModified > oldLastModified) {
				oldLastModified = newLastModified;
				// 如果文件变了，重新加载
				System.out.println("file changed, reload PrintModule");
				ModuleManager.dynamicLoad("PrintModule");
			}
		}
	}
}
